#! /usr/bin/python

# ***********************************************************************
# Copyright (c) 2017 Unity Technologies. All rights reserved.
#
# Licensed under the ##LICENSENAME##.
# See LICENSE.md file in the project root for full license information.
# ***********************************************************************

import os
import re
import sys
import time

# Input:
# 1- full path to the output .i file
# 2..n- full path to the fbx header file(s) to read
#
# Output:
# - a swig .i file to be %included at the end of a .i file,
#   to include all the constants as %fbximmutable
#
# Each line is matched against each regex. We emit the replacement into
# an %fbximmutable line. 
#
# It's almost impossible to properly pass a regex from cmake into python via a
# command-line in a platform-independent way, so we don't try. Instead, this
# file maps the .i file's basename to the regexes to apply.
#
# Example:
#     discover-immutables fbxdatatypeconstants.i bar.h
# The script will read bar.h line by line. When it sees a line that matches:
#     extern FBXSDK_DLL FbxDataType FbxDoubleDT;
# then the script will add a line to foo.i that reads:
#     %fbximmutable(FbxDoubleDT);
# This is because 'foo.i' maps to the regex pattern/repl pair:
#     (r'extern FBXSDK_DLL FbxDataType ([a-zA-Z0-9_]+)', r'\1')
# One output file can map to many regex pairs.

output_filename = sys.argv[1]

# e.g. "FbxPropertyT<EBlendMode>        CurrentTextureBlendMode;"
propertyTmember = (re.compile(r'\s*FbxPropertyT<[a-zA-Z0-9_]+>\s*([a-zA-Z0-9_]+)\s*;\s*'), r'\1')

# e.g. "FbxProperty LastSaved;"
propertymember = (re.compile(r'\s*FbxProperty\s*([a-zA-Z0-9_]+)\s*;\s*'), r'\1')

# e.g. "static const char* sVectorSpace        ;"
staticstring = (re.compile(r'\s*static\s*const\s*char\s*\*\s*([a-zA-Z0-9_]+)\s*;\s*'), r'\1')

# The default substitutions to use.
default_pairs = ( propertyTmember, propertymember, staticstring )

# You can override the default for a target by adding entries here.
# This maps the basename of the target to a list. Each entry in the list is a pair
# that defines the query and the substitution for a call to re.sub.
regex_pairs = {
  'fbxdatatypeconstants.i' : [(re.compile(r'\s*extern FBXSDK_DLL FbxDataType ([a-zA-Z0-9_]+);\s*'), r'\1')],
}

# Look up the regular expressions for this target file.
subs = regex_pairs.get(os.path.basename(output_filename), default_pairs)

with open(output_filename, 'w') as outfile:
  outfile.write("/* Automatically generated by {} at {} */\n\n".format(
    sys.argv[0], time.ctime()));
  for infilename in sys.argv[2:]:
    with open(infilename) as infile:
      for line in infile:
        for (pattern, replacement) in subs:
          munged = pattern.sub(replacement, line)
          if munged != line:
            outfile.write("%fbximmutable({});\n".format(munged))
